import 'dart:async';
import 'package:flutter/material.dart';
import 'package:gksz/political_Theory/Video/BottomInput.dart';
import 'package:share/share.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

Dio dio = new Dio();

class MessagePage extends StatefulWidget {
  final msg;
  MessagePage({Key key, @required this.msg}) : super(key: key);
  _MessagePageState createState() => _MessagePageState(this.msg);
}

class _MessagePageState extends State<MessagePage> {
  final msg;
  var cang;
  String backResult;
  bool _isFavorited = false;
  void _toggleFavorite() {
    setState(() {
      // If the lake is currently favorited, unfavorite it.
      if (_isFavorited) {
        _isFavorited = false;
        // Otherwise, favorite it.
      } else {
        _isFavorited = true;
      }
    });
  }

  void shoucang() async {
    //收藏
    if (number.length == 10) {
      Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/collect?query={"studentId":"${user_id}","news":"${msg['_id']}"}');
    cang = response.data;
    }else{
      Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/collect?query={"teacherId":"${user_id}","news":"${msg['_id']}"}');
    cang = response.data;
    }
    
    // print(cang);
    setState(() {});
  }

  var _res;
  void message() async {
    //评论
    Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/Comment?query={"videoId":"${msg['_id']}"}&sort=-createAt');
    _res = response.data;
    setState(() {});
    print(_res);
  }

  var user_id;
  var number;
  getName() async {
    //获取Id
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    user_id = sharedPreferences.getString('user_id');

    number = sharedPreferences.getString('number');
    shoucang(); // 初始化根据ID拉取收藏数据11
    missionpoint();
    setState(() {});
  }

  var _point;
  void missionpoint() async {
    if (number.length == 10) {
      Response response = await dio
          .get('http://xssw.gdit.edu.cn/sizheng/api/v1/student/${user_id}');
      _point = response.data;
    } else {
      Response response = await dio
          .get('http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${user_id}');
      _point = response.data;
    }

    // print(_point['mission']['yaowen']);
    setState(() {});
  }

  Timer _timer;
  void countdown() {
    _timer = new Timer(new Duration(seconds: 120), () async {
      if (number.length == 10) {
        if (_point['mission']['studyTime'] == 'false') {
          var newpoint = _point['point'] + 2;
          var pp = await dio.patch(
              'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${user_id}',
              data: {'point': newpoint});
          var zhuangtai = await dio.patch(
              'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${user_id}',
              data: {
                "mission": {
                  "studyTime": "true",
                }
              });
        }
      } else {
        if (_point['mission']['studyTime'] == 'false') {
          var newpoint = _point['point'] + 2;
          var pp = await dio.patch(
              'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${user_id}',
              data: {'point': newpoint});
          var zhuangtai = await dio.patch(
              'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${user_id}',
              data: {
                "mission": {
                  "studyTime": "true",
                }
              });
        }
      }
    });
  }

  @override
  void initState() {
    super.initState();
    getName();
    message();
    countdown();
  }

  _MessagePageState(this.msg);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 5.0),
            child: Text(
              '${msg['title']}',
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.w600),
            ),
          ),
          Container(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  width: 200.0,
                  margin: EdgeInsets.only(left: 10.0, top: 10, right: 10.0),
                  child: Text(
                    '来源：' + '${msg['from']}',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 5.0, top: 10, right: 10.0),
                  child: Text(
                    '${msg['createdAt'].substring(0, 10)}',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ),
              ],
            ),
          ),
          Center(
              child: Html(
            padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
            data: '${msg['contain']}',
            defaultTextStyle: TextStyle(fontSize: 16),
          )),
          Container(
            //评论
            margin: EdgeInsets.only(left: 5.0, right: 10.0, top: 10.0),
            child: Row(
              children: <Widget>[
                Text("丨",
                    style: TextStyle(
                        fontSize: 25.0,
                        color: Colors.red,
                        fontWeight: FontWeight.w900)),
                Text(
                  "评论",
                  style: TextStyle(fontSize: 18.0),
                )
              ],
            ),
          ),
          _res == null
              ? Container(
                  margin: EdgeInsets.fromLTRB(0, 50, 0, 50),
                  alignment: Alignment.center,
                  child: Text(
                    '暂无评论',
                    style: TextStyle(fontSize: 18.0),
                  ),
                )
              : _res.length == 0
                  ? Container(
                      //没有评论
                      margin: EdgeInsets.fromLTRB(0, 50, 0, 50),
                      alignment: Alignment.center,
                      child: Text(
                        '暂无评论',
                        style: TextStyle(fontSize: 18.0),
                      ),
                    )
                  : Container(
                      //有评论
                      // margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
                      child: ListView.builder(
                        itemCount: _res.length,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (context, index) {
                          return ListTile(
                              title: Row(
                                children: <Widget>[
                                  Container(
                                      width: 30.0,
                                      height: 30.0,
                                      decoration: ShapeDecoration(
                                          shape: CircleBorder(),
                                          image: DecorationImage(
                                              fit: BoxFit.cover,
                                              image: AssetImage(
                                                "images/head.jpg",
                                              )))),
                                  Container(
                                    margin:
                                        EdgeInsets.only(left: 10, bottom: 10),
                                    child: Text(
                                      '${_res[index]['name']}',
                                      style: TextStyle(
                                          color: Colors.red, fontSize: 16.0),
                                    ),
                                  ),
                                  _res[index]['userId'] == user_id
                                      ? Container(
                                          width: 30,
                                          height: 16,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(15),
                                            color: Colors.blue,
                                          ),
                                          margin: EdgeInsets.only(
                                              left: 10, bottom: 10),
                                          child: Text(
                                            "我",
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: Colors.white),
                                          ),
                                        )
                                      : Container()
                                ],
                              ),
                              subtitle: Column(
                                children: <Widget>[
                                  Container(
                                    width: MediaQuery.of(context).size.width *
                                        4 /
                                        5,
                                    margin: EdgeInsets.only(
                                      left: 40,
                                      right: 20,
                                    ),
                                    padding: EdgeInsets.only(bottom: 10),
                                    child: Text(
                                      "${_res[index]['contain']}",
                                      style: TextStyle(
                                          fontSize: 16.0, color: Colors.black),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(40, 0, 0, 5),
                                    child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: <Widget>[
                                      Text('${_res[index]['createAt'].substring(0, 10)}'),
                                      _res[index]['userId'] == user_id
                                      ? Container(
                                          //删除按钮
                                          // width:
                                              // MediaQuery.of(context).size.width,
                                          // alignment: Alignment.centerLeft,
                                          // padding: EdgeInsets.only(
                                          //     left: 40.0, bottom: 5.0),
                                          child: InkWell(
                                            child: Text(
                                              '删除',
                                              style: TextStyle(
                                                  fontSize: 14.0,
                                                  decoration:
                                                      TextDecoration.underline),
                                            ),
                                            onTap: () async {
                                              Dio dio = new Dio();
                                              showDialog<Null>(
                                                context: context,
                                                barrierDismissible: false,
                                                builder:
                                                    (BuildContext context) {
                                                  return new AlertDialog(
                                                    content:
                                                        new SingleChildScrollView(
                                                      child: new ListBody(
                                                        children: <Widget>[
                                                          new Text('是否删除该条评论'),
                                                        ],
                                                      ),
                                                    ),
                                                    actions: <Widget>[
                                                      new Row(
                                                        children: <Widget>[
                                                          FlatButton(
                                                            child:
                                                                new Text('确定'),
                                                            onPressed:
                                                                () async {
                                                              Response
                                                                  response =
                                                                  await dio
                                                                      .delete(
                                                                "http://xssw.gdit.edu.cn/sizheng/api/v1/Comment/" +
                                                                    '${_res[index]['_id']}',
                                                              );
                                                              message();
                                                              Navigator.of(
                                                                      context)
                                                                  .pop();
                                                            },
                                                          ),
                                                          FlatButton(
                                                            child:
                                                                new Text('取消'),
                                                            onPressed: () {
                                                              Navigator.of(
                                                                      context)
                                                                  .pop();
                                                            },
                                                          ),
                                                        ],
                                                      )
                                                    ],
                                                  );
                                                },
                                              );
                                            },
                                          ))
                                      : Container(),
                                    ],
                                  ),
                                  ),
                                  Container(
                                    decoration: BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                width: 1,
                                                color: Color(0xffe5e5e5)))),
                                  )
                                ],
                              ));
                        },
                      ),
                    )
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        //底部栏
        child: Container(
            height: 50.0,
            width: MediaQuery.of(context).size.width,
            // margin: EdgeInsets.only(left: 30.0,right: 30.0),
            // child: SingleChildScrollView(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                    width: MediaQuery.of(context).size.width * 2 / 3,
                    child: Container(
                        color: Colors.grey[300],
                        margin: EdgeInsets.all(10),
                        padding: EdgeInsets.fromLTRB(15, 5, 10, 5),
                        height: 30,
                        child: InkWell(
                          child: Text("欢迎发表你的评论"),
                          onTap: () async {
                            // message();
                            await Navigator.push(
                                    context,
                                    PopRoute(
                                        child: BottomInputDialog(
                                            videoId: '${msg['_id']}')))
                                .then((userInfo) {
                              setState(() {
                                backResult = userInfo;
                                if (backResult.length > 0) {
                                  message();
                                  showDialog<Null>(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return new AlertDialog(
                                        content: new SingleChildScrollView(
                                          child: new ListBody(
                                            children: <Widget>[
                                              new Text('评论发表成功'),
                                            ],
                                          ),
                                        ),
                                        actions: <Widget>[
                                          new FlatButton(
                                            child: new Text('确定'),
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                          ),
                                        ],
                                      );
                                    },
                                  );
                                }
                              });
                            });
                            // print(backResult.isEmpty);
                          },
                        ))),
                Container(
                  child: Row(
                    // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                          // margin: EdgeInsets.fromLTRB(28.0, 0.0, 20.0, 0.0),
                          height: 40,
                          width: MediaQuery.of(context).size.width / 6,
                          child: InkWell(
                            child: Container(
                              alignment: Alignment.center,
                              child: cang != null
                                  ? Image.asset(
                                      cang.length != 0
                                          ? 'images/star2.png'
                                          : 'images/star1.png',
                                      width: 25,
                                      height: 25,
                                    )
                                  : Image.asset(
                                      'images/star1.png',
                                      width: 25,
                                      height: 25,
                                    ),
                            ),
                            onTap: () async {
                              //判断数组中是否已经收藏
                              if (number.length == 10) {
                                if (cang.length == 0) {
                                  Response response = await dio.post(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect",
                                      data: {
                                        'studentId': '$user_id',
                                        'news': '${msg['_id']}'
                                      });
                                } else {
                                  Response response = await dio.delete(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect/"+'${cang[0]['_id']}');
                                }
                                
                              }else{
                                if (cang.length == 0) {
                                  Response response = await dio.post(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect",
                                      data: {
                                        'teacherId': '$user_id',
                                        'news': '${msg['_id']}'
                                      });
                                } else {
                                  Response response = await dio.delete(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect/"+'${cang[0]['_id']}');
                                }
                              }
                             shoucang();
                              setState(() {});
                            },
                          )),
                      Container(
                          width: MediaQuery.of(context).size.width / 6,
                          height: 60.0,
                          child: InkWell(
                            child: Icon(
                              Icons.share,
                              size: 25.0,
                              color: Colors.grey[800],
                            ),
                            onTap: () {
                              Share.share(
                                  '${msg['title']}' + '<<<<复制这段话后打开最新版【广科思政】');
                            },
                          )),
                    ],
                  ),
                )
              ],
            )
            // )
            ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    getName();
    message();
    // countdown();
    _timer.cancel();
  }
}
